<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>系统管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户列表</el-breadcrumb-item>

		</el-breadcrumb>
		<!-- 卡片式图 -->
		<el-card class="box-card">
			<!-- 搜索添加区 -->

			<el-row :gutter="20">
				<el-col :span="8">
					<!-- @clear 绑定getuserlist 点击文本清除时重新搜索数据 -->
					<el-input @clear="getuserlist" clearable placeholder="请输入内容" v-model="queryinfo.query"
						class="input-with-select">
						<el-button slot="append" icon="el-icon-search" @click="getuserlist"></el-button>
					</el-input>
				</el-col>
				<el-col :span="4">
					<el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
				</el-col>
			</el-row>
			<!-- 用户列表区 -->
			<el-table border stripe :data="userlist" style="width: 100%">
				<el-table-column type="index" label="#">
				</el-table-column>
				<el-table-column prop="username" label="姓名" width="180">
				</el-table-column>
				<el-table-column prop="email" label="邮箱" width="180">
				</el-table-column>
				<el-table-column prop="mobile" label="电话">
				</el-table-column>
				<el-table-column prop="role_name" label="角色">
				</el-table-column>
				<el-table-column label="状态">
					<!-- slot-scope="scope" 获取当前行数据 -->
					<template slot-scope="scope">
						<el-switch @change="userStateChanged(scope.row)" v-model="scope.row.mg_state"
							active-color="#13ce66" inactive-color="#ff4949">
						</el-switch>
					</template>
				</el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<!-- 修改按钮 -->
						<el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">
						</el-button>
						<!-- 删除按钮 -->
						<el-button type="danger" icon="el-icon-delete" size="mini"
							@click="removeUserById(scope.row.id)"></el-button>
						<el-tooltip effect="dark" content="角色分配" placement="top" :enterable="false">
							<!-- 角色分配按钮 -->
							<el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)">
							</el-button>
						</el-tooltip>

					</template>

				</el-table-column>
			</el-table>
			<!-- 分页区 -->
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="queryinfo.pagenum" :page-sizes="[2,5,10]" :page-size="queryinfo.pagesize"
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</el-card>
		<!-- 添加用户的对话框 -->
		<el-dialog title="添加用户:" @close="addDialogclosed" :visible.sync="addDialogVisible" width="50%">
			<!-- 内容主体区域 -->

			<el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
				<el-form-item label="用户名:" prop="username">
					<el-input v-model="addForm.username"></el-input>
				</el-form-item>
				<el-form-item label="密码:" prop="password">
					<el-input v-model="addForm.password"></el-input>
				</el-form-item>
				<el-form-item label="邮箱:" prop="email">
					<el-input v-model="addForm.email"></el-input>
				</el-form-item>
				<el-form-item label="手机:" prop="mobile">
					<el-input v-model="addForm.mobile"></el-input>
				</el-form-item>
			</el-form>

			<!-- 底部区域 -->
			<span slot="footer" class="dialog-footer">
				<el-button @click="addDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="addUser()">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 修改用户的对话框 -->
		<el-dialog title="修改用户" @close="editDialogclosed" :visible.sync="editDialogVisible" width="50%">
			<el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="70px">
				<el-form-item label="用户名">
					<el-input disabled v-model="editForm.username"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="editForm.email"></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="mobile">
					<el-input v-model="editForm.mobile"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="edituserinfo">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 分配角色的对话框 -->
		<el-dialog title="分配角色" :visible.sync="setRoledialogVisible" width="50%" @close="setRoleDialogClosed">
			<div>
				<p>当前用户：{{userinfo.username}}</p>
				<p>当前用户角色：{{userinfo.role_name}}</p>
				<p>分配新角色：
					<template>
						<el-select v-model="selectedRoleId" placeholder="请选择">
							<el-option v-for="item in roleslist" :key="item.id" :label="item.roleName" :value="item.id">
							</el-option>
						</el-select>
					</template>
				</p>
			</div>

			<span slot="footer" class="dialog-footer">
				<el-button @click="setRoledialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="saveRoleInfo">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		data() {
			// 验证邮箱的规则
			var checkEmail = (rule, value, cb) => {
				//验证邮箱的正则表达式
				const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

				if (regEmail.test(value)) {
					//合法的邮箱
					return cb()
				}
				cb(new Error('请输入合法的邮箱'))

			}

			//验证手机号的规则
			var checkMobile = (rule, value, cb) => {
				//验证手机号的正则
				const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
				if (regMobile.test(value)) {
					return cb();
				}
				cb(new Error('请输入合法的手机号'))
			}
			return {
				//获取用户列表参数对象
				queryinfo: {
					query: '',
					//当前的页数
					pagenum: 1,
					//当前每页显示多少条数据
					pagesize: 5
				},
				//添加用户的表单数据
				addForm: {
					username: '',
					password: '',
					email: '',
					mobile: ''
				},
				//添加用户表单验证的验证规则对象
				addFormRules: {
					username: [{
							required: true,
							message: '请输入用户名',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 10,
							message: '用户名的长度在3~10之间',
							trigger: 'blur'
						}
					],
					password: [{
							required: true,
							message: '密码',
							trigger: 'blur'
						},
						{
							min: 6,
							max: 15,
							message: '密码的长度在6~15之间',
							trigger: 'blur'
						}
					],
					email: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkEmail,
							trigger: 'blur'
						}
					],
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: 'blur'
						},
						{
							validator: checkMobile,
							trigger: 'blur'
						}
					]
				},
				//编辑用户表单验证对象
				editFormrules: {
					email: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkEmail,
							trigger: 'blur'
						}
					],
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: 'blur'
						},
						{
							validator: checkMobile,
							trigger: 'blur'
						}
					]
				},
				// 存放用户列表数据
				userlist: [],
				//数据总条数
				total: 0,
				//控制添加用户对话框的显示和隐藏
				addDialogVisible: false,
				//控制修改对话框的显示和隐藏
				editDialogVisible: false,
				//用户查询到的用户信息对象
				editForm: {

				},
				//控制分配角色对话框的显示与隐藏
				setRoledialogVisible: false,
				//需要被分配角色的用户信息
				userinfo: {},
				//角色列表
				roleslist: [],
				//存放选中下拉列表中的值
				selectedRoleId: ''


			};
		},
		created() {
			this.getuserlist()
		},
		methods: {
			async getuserlist() {
				const {
					data: res
				} = await this.$http.get('users', {
					params: this.queryinfo
				})
				if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
				this.userlist = res.data.users
				this.total = res.data.total
			},
			//监听pagesize改变的事件
			handleSizeChange(newSize) {
				this.queryinfo.pagesize = newSize
				this.getuserlist()
			},
			//监听页面值改变的事件
			handleCurrentChange(newPage) {
				this.queryinfo.pagenum = newPage
				this.getuserlist()
			},
			//修改用户信息事件
			async userStateChanged(userinfo) {
				const {
					data: res
				} = await this.$http.put(`users/${userinfo.id}
			/state/${userinfo.mg_state}`)
				if (res.meta.status != 200) {
					userinfo.mg_state = !userinfo.mg_state
					return this.$message.error(res.meta.msg)
				} else {
					return this.$message.success(res.meta.msg)
				}


			},
			//监听添加用户对话框的关闭事件清除input内容
			addDialogclosed() {
				this.$refs.addFormRef.resetFields()

			},
			//点击按钮添加新用户
			addUser() {
				this.$refs.addFormRef.validate(async valid => {
					if (!valid) return
					//可以发起用户请求
					const {
						data: res
					} = await this.$http.post('users', this.addForm)
					if (res.meta.status != 201) {
						this.$message.success(res.meta.msg)
					}
					this.$message.success(res.meta.msg)


					//隐藏添加用户的对话框
					this.addDialogVisible = false

					//重新获取用户列表数据
					this.getuserlist()

				})
			},
			//展示编辑用户对话框
			async showEditDialog(id) {
				const {
					data: res
				} = await this.$http.get('users/' + id)
				if (res.meta.status != 200) {
					return this.$message.error("查询用户数据失败")
				}
				this.editForm = res.data
				this.editDialogVisible = true
			},
			//监听用户修改对话框的关闭事件重置input框
			editDialogclosed() {
				this.$refs.editFormRef.resetFields()
			},
			//修改用户信息并提交
			edituserinfo() {
				this.$refs.editFormRef.validate(async valid => {

					if (!valid) return
					const {
						data: res
					} = await this.$http.put('users/' + this.editForm.id, {
						email: this.editForm.email,
						mobile: this.editForm.mobile
					})

					if (res.meta.status != 200) {
						return this.$message.error("更新用户数据失败")
					}
					//关闭对话框
					this.editDialogVisible = false
					//刷新列表
					this.getuserlist()
					//提示成功
					return this.$message.success("更新成功")

				})
			},
			//移除用户事件
			async removeUserById(id) {
				const confirmResult = await this.$confirm('此操作将永久删除用户, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					//如果用户取消删除则 则打印cancel字符串
					.catch(err => err)
				//如果用户确认删除则confirmResult 为confim字符串

				if (confirmResult != 'confirm') {
					return this.$message.info("已经取消删除")
				}
				const {
					data: res
				} = await this.$http.delete('users/' + id)
				if (res.meta.status != 200) {
					this.$message.error("删除失败" + res.meta.msg)
				}
				this.$message.success("删除成功")
				this.getuserlist();
			},
			//展示用户分配角色对话框
			async setRole(userinfo) {
				this.userinfo = userinfo
				//展示对话框之前获取所有用户角色列表
				const {
					data: res
				} = await this.$http.get('roles')
				if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
				this.roleslist = res.data
				this.setRoledialogVisible = true
			},
			//点击确定提交分配用户角色
			async saveRoleInfo() {
				//用户没有选择时
				if (!this.selectedRoleId) {
					return this.$message.info("请选择要分配的角色")
				}
				const {
					data: res
				} = await this.$http.put(`users/${this.userinfo.id}/role`, {
					rid: this.selectedRoleId
				})
				if (res.meta.status != 200) {
					this.$message.error("更新失败" + res.meta.msg)
				}
				this.$message.success("分配成功")
				this.getuserlist()
				this.setRoledialogVisible = false
			},
			//监听分配角色对话框关闭时重置数据
			setRoleDialogClosed() {
				this.userinfo = {};
				this.selectedRoleId = ''
			}

		}
	}
</script>

<style lang="less" scoped>

</style>
